﻿using UnityEngine;
using UnityEditor;

namespace CWM.Skinn
{
    public static partial class SkinnContextCommands
    {
        [CtxMenuItem("Transform/Export/Transforms", 
            "Exports a Transform and it's children in a fbx file.",
            ContextRequirements.SingleItem, 0)]
        public static void TransformsExport()
        {
            foreach (var item in SkinnContext.GetContextItems())
            {
                var context = item.GetComponent<Transform>();
                if (SkinnEx.IsNullOrNotInAScene(context)) continue;
                string path = EditorUtility.SaveFilePanelInProject("Export FBX", context.name, "fbx", "ACSIIFBX");
                if (path == "") continue;
                if (!path.EndsWith(".fbx")) Debug.LogWarning("file path should end with .FBX");
                string fbx = context.gameObject.ToACSIIFBX();
                if (string.IsNullOrEmpty(fbx)) continue;
                if (System.IO.File.Exists(path)) AssetDatabase.DeleteAsset(path);
                System.IO.File.WriteAllText(path, fbx);
                AssetDatabase.Refresh();
                break;
            }
            SkinnContext.Finished();
        }

        [CtxMenuItem("Transform/Export/Transforms For Avatar",
            "Exports a Transform and it's children in a fbx file. " +
            "Includes a temp mesh to keep the model importer from crashing when creating a avatar.",
            ContextRequirements.SingleItem, 0)]
        public static void TransformsAvatarExport()
        {
            foreach (var item in SkinnContext.GetContextItems())
            {
                var context = item.GetComponent<Transform>();
                if (SkinnEx.IsNullOrNotInAScene(context)) continue;
                string path = EditorUtility.SaveFilePanelInProject("Export FBX", context.name, "fbx", "ACSIIFBX");
                if (path == "") continue;
                if (!path.EndsWith(".fbx")) Debug.LogWarning("file path should end with .FBX");
                string fbx = context.gameObject.ToACSIIFBX(true);
                if (string.IsNullOrEmpty(fbx)) continue;
                if (System.IO.File.Exists(path)) AssetDatabase.DeleteAsset(path);
                System.IO.File.WriteAllText(path, fbx);
                AssetDatabase.Refresh();
                break;
            }
            SkinnContext.Finished();

        }
    }
}